package id.co.rho.scoring.cid.client.mvc.score;

import id.co.rho.scoring.cid.client.command.CommandDispatcherAsync;
import id.co.rho.scoring.cid.client.command.impl.ModelSearchCommandAction;
import id.co.rho.scoring.cid.client.command.impl.ModelSearchCommandResult;
import id.co.rho.scoring.cid.client.managed.request.ApplicationRequestFactory;
import id.co.rho.scoring.cid.client.mvc.AppEvents;
import id.co.rho.scoring.cid.client.security.Credential;

import java.util.List;

import com.extjs.gxt.ui.client.data.ModelData;
import com.extjs.gxt.ui.client.mvc.AppEvent;
import com.extjs.gxt.ui.client.mvc.Controller;
import com.extjs.gxt.ui.client.mvc.View;
import com.extjs.gxt.ui.client.store.ListStore;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.inject.Inject;

public class UploadAnswerView extends View {

	private CommandDispatcherAsync dispatcher;
	private Credential credential;
	private UploadAnswerUI uploadAnswerUI;

	@Inject
	public UploadAnswerView(CommandDispatcherAsync dispacther,
			Credential credential, UploadAnswerUI uploadAnswerUI) {
		super(null);
		this.dispatcher = dispacther;
		this.credential = credential;
		this.uploadAnswerUI = uploadAnswerUI;
		controller = new ViewController();

	}

	@Override
	public void initialize() {
		super.initialize();
		uploadAnswerUI.initialize();
	}

	@Override
	protected void handleEvent(AppEvent event) {
		if (event.getType().equals(AppEvents.UploadAnswerEvent)) {
			uploadAnswerUI.show();
			searchModel();
		}
	}

	public void searchModel() {
		ModelSearchCommandAction action = new ModelSearchCommandAction();
		action.setName(null);
		dispatcher.execute(action,
				new AsyncCallback<ModelSearchCommandResult>() {
					@Override
					public void onFailure(Throwable caught) {
					}

					@Override
					public void onSuccess(ModelSearchCommandResult result) {
						List<ModelData> models = (List<ModelData>) result
								.getModels();
						ListStore<ModelData> modelStore = new ListStore<ModelData>();
						for (ModelData model : models) {
							modelStore.add(model);
						}
						uploadAnswerUI.setModels(modelStore);
					}

				});

	}

	private class ViewController extends Controller {
		private ViewController() {
			registerEventTypes(AppEvents.UploadAnswerEvent);
		}

		@Override
		public void handleEvent(AppEvent event) {
			forwardToView(UploadAnswerView.this, event);
		}
	}

}
